﻿using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Cofe.Core.Interfaces;

namespace Cofe.Core.Implements
{
    [Export(typeof(ICofeService))]
    [ServicePriority(ServicePriorityAttribute.DefaultPriority_COFE)]
    public class VolumeRegistrarBehaviorManager : IVolumeRegistrarBehaviorManager
    {
        public VolumeRegistrarBehaviorManager()
        {

        }

        public VolumeRegistrarBehaviorManager(IVolumeRegistrarGetRootBehavior[] getRootBehavior)
        {
            _getRootBehavior = getRootBehavior;
        }

        private IVolumeRegistrarGetRootBehavior[] _getRootBehavior = null;
        private IVolumeChangedBehavior[] _volChangedBehavior = null;


        public IVolumeRegistrarGetRootBehavior[] GetRootBehaviors
        {
            get
            {
                return _getRootBehavior ?? (_getRootBehavior = CofeServices.ServiceLocater
                    .FindAllServices<IVolumeRegistrarGetRootBehavior>().ToArray());
            }
        }


        public IVolumeChangedBehavior[] VolumeChangedBehaviors
        {
            get
            {
                return _volChangedBehavior ?? (_volChangedBehavior = CofeServices.ServiceLocater
                    .FindAllServices<IVolumeChangedBehavior>().ToArray());
            }
        }

        public IEnumerable<Property.IPropertyHost> GetRootPropertyHosts(EntryConstructionFlags flags)
        {
            foreach (var b in GetRootBehaviors)
                if (b.SupportedConstructionFlags.Contains(flags))
                    return b.GetRootPropertyHosts();
            throw new NotSupportedException("flags");
        }

        public IEnumerable<ICofeDirectoryInfo> GetRootDirectories(EntryConstructionFlags flags)
        {
            return from rph in CofeServices.VolumeRegistrar.Behaviors.GetRootPropertyHosts(flags)
                   select CofeServices.EntryConstructor.ConstructEntryAsync<ICofeDirectoryInfo>(rph).Result;
        }


    }
}
